<template>
  <ContentWrap class="chem-record-wrap">
    <div class="header-container-consumable">
      <!-- Title Centered -->
      <h2 class="centered-title-equipment"> 气质联用定性分析原始记录[{{ form.sampleNo }}]</h2>
    </div>
    <!-- 检测结果表格 -->
    <div class="11table-section">
      <!--      <div class="table-header">-->
      <!--        <h3 class="table-title">检出的挥发性有机组分</h3>-->
      <!--      </div>-->
      <el-table
        :data="filteredTableData"
        :span-method="spanMethod"
        border
        class="chem-table"
        stripe
        table-layout="fixed"
      >
        <el-table-column align="center" label="序号" type="index" width="80" />
        <el-table-column align="center" label="代表/取样场所、岗位、地点" prop="post" >
          <template #default="{ row }">
            <el-input v-model="row.post" placeholder="" :disabled="props.tbflag" :title="row.post"/>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="检出的挥发性有机组分名称"
          width="180px"
          prop="componentName"
        >
          <template #default="{ row }">
            <el-input v-model="row.componentName" placeholder="请输入组分名称" :disabled="props.tbflag" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="CAS号" prop="casNo" width="100">
          <template #default="{ row }">
            <el-input v-model="row.casNo" placeholder="请输入CAS号" :disabled="props.tbflag" />
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="峰面积百分比(%)"
          prop="peakAreaPercentage"
          width="150"
        >
          <template #default="{ row }">
            <el-input
              v-model="row.peakAreaPercentage"
              placeholder="0.00"
              :disabled="props.tbflag"
              @input="calculateTotalPercentage"
            />
          </template>
        </el-table-column>
        <el-table-column align="center" label="备注" width="60" prop="remark" v-if="!props.tbflag">
          <template #default="{ row }">
            <el-input v-model="row.remark" placeholder="" :disabled="props.tbflag" />
          </template>
        </el-table-column>
        <el-table-column align="center" fixed="right" label="操作" width="150" v-if="!props.tbflag">
          <template #default="{  $index }">
            <div style="display: flex; gap: 8px; justify-content: center;">
              <el-button
                size="small"
                type="primary"
                @click="addRow($index)"
                :disabled="props.tbflag"
              >
                新增
              </el-button>
              <el-button
                :disabled="form.table.length <= 1 || props.tbflag"
                size="small"
                type="danger"
                @click="removeSpecificRow($index)"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </ContentWrap>
</template>

<script lang="ts" setup>
import { onMounted, ref, watch, computed } from 'vue'
import ContentWrap from '@/components/ContentWrap/src/ContentWrap.vue'
import { ElButton, ElMessage } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import { merge } from 'lodash-es'

const route = useRoute()
const router = useRouter()
const props = defineProps<{
  volatileItem?: Record<string, any>
  tbflag: boolean
}>()
const form = ref({
  projectId: route.query.projectId,
  taskNo: '',
  detectionType: '定期检测',
  sampleName: '',
  sampleNo: '',
  detectionItem: '挥发有机组分定性及峰面积百分比测定',
  temperature: '26',
  humidity: '50',
  submissionDate: '',
  testDate: new Date().toISOString().split('T')[0],
  testStandard:
    'GDOHTQC 001-2020《化学品中挥发性有机组分定性分析和峰面积百分比测定顶空气相色谱-质谱法》',
  reportMethod:
    '有机挥发物成分按峰面积归一法计算各组分相对百分含量；有机挥发物的定性结果与标准谱库匹配度小于     %，为其他物质。',
  instrumentName: '气质联用仪',
  instrumentModel: '7890B-5977B',
  instrumentSerial: 'HAYQ2053',
  instrumentInfo: '',
  columnName: 'HP-VOC',
  columnLength: '60',
  innerDiameter: '0.2',
  filmThickness: '1.12',
  columnTempProgram: '',
  vaporizationTemp: '250',
  scanMode: '全扫描',
  carrierGasFlow: '1.0',
  scanRange: '10-550',
  auxiliaryTemp: '250',
  solventDelay: '0',
  ionSourceTemp: '230',
  splitRatio: '10:1',
  quadrupoleTemp: '150',
  injectionVolume: '1.0',
  sampleTreatment: '称取5.0g样品于20mL顶空瓶中,于40℃电热恒温鼓风干燥箱中加热平衡30min。',
  qualitativeAnalysis: '对检出组分的峰面积进行归一法计算,得到各组分的峰面积百分比。',
  totalVolatileOrganicPercentage: '',
  inorganicPercentage: '',
  table: [
    {
      retentionTime: '',
      componentName: '苯',
      casNo: '71-43-2',
      peakAreaPercentage: '未检出',
      remark: ''
    },
    {
      retentionTime: '',
      componentName: '1,2-二氯乙烷',
      casNo: '107-06-2',
      peakAreaPercentage: '未检出',
      remark: ''
    },
    {
      retentionTime: '',
      componentName: '正己烷',
      casNo: '110-54-3',
      peakAreaPercentage: '未检出',
      remark: ''
    },
    {
      retentionTime: '',
      componentName: '三氯乙烯',
      casNo: '79-01-6',
      peakAreaPercentage: '未检出',
      remark: ''
    },
    {
      retentionTime: '',
      componentName: '丙酮',
      casNo: '67-64-1',
      peakAreaPercentage: '未检出',
      remark: ''
    }
  ]
})

const emit = defineEmits(['change'])
const loading = ref(true)

// 直接使用原始表格数据，不做过滤
const filteredTableData = computed(() => {
  return form.value.table
})


// 计算表格中峰面积百分比的总和
const calculateTotalPercentage = () => {
  const totalPercentage = form.value.table.reduce((sum, row) => {
    const percentage = parseFloat(row.peakAreaPercentage) || 0
    return sum + percentage
  }, 0)

  // 自动更新总挥发性有机组分百分比
  form.value.totalVolatileOrganicPercentage = totalPercentage.toFixed(3)

  // 计算无机组分百分比
  const inorganicPercentage = 100 - totalPercentage
  form.value.inorganicPercentage = inorganicPercentage.toFixed(3)

  // 验证总和是否为100%
  if (Math.abs(totalPercentage + inorganicPercentage - 100) > 0.1) {
    ElMessage.warning('各组分峰面积百分比总和应为100%')
  }
}

// 新增行
const addRow = (index: number) => {
  // 在当前行后面插入新行
  const newRow = {
    retentionTime: '',
    componentName: '',
    casNo: '',
    peakAreaPercentage: '',
    remark: '',
    post: form.value.table[index]?.post || '' // 继承当前行的 post 值，保持合并单元格逻辑
  }
  form.value.table.splice(index + 1, 0, newRow)
}

// 删除指定行
const removeSpecificRow = (index: number) => {
  if (form.value.table.length > 1) {
    form.value.table.splice(index, 1)
    calculateTotalPercentage()
  }
}

watch(
  () => props.volatileItem,
  (newValue, oldValue) => {
    console.log('form changed1111:', newValue)
    // 只有在 newValue 存在且与当前 form 不同时才更新
    if (newValue && JSON.stringify(newValue) !== JSON.stringify(form.value)) {
      form.value = merge({}, form.value, newValue)
      if (!loading.value) {
        ElMessage.success('修改成功')
        loading.value = false
      }
    }
  },
  { deep: true, immediate: true } // 深度监听，因为 form 是嵌套对象
)

// 监听表单数据变化
watch(
  form,
  (newVal) => {
    emit('change', newVal)
    console.log('表单数据全部变化111:', JSON.stringify(newVal))
  },
  { deep: true }
)

onMounted(async () => {
  loading.value = false
})

// 允许父组件通过 ref 访问并设置表单
defineExpose({ form })
</script>

<style lang="scss" scoped>
.header-container-consumable {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 1px solid #e5e6eb;
}

.centered-title-equipment {
  text-align: center; // Center the text
  flex-grow: 1; // Allow title to take available space to help centering
  margin: 0; // Remove default margin
  font-size: 24px; // Match Consumable title size
  font-weight: bold;
}

.chem-form {
  background: none;
  box-shadow: none;
  border-radius: 0;
  margin-bottom: 0;

  :deep(.el-input__inner) {
    border-radius: 0 !important;
    box-shadow: none !important;
  }

  :deep(.el-form-item__label) {
    white-space: nowrap;
  }
}

.chem-btns {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  align-items: center;
  margin-top: 0;
}

.chem-table {
  margin-top: 18px;
  --el-table-border-radius: 0 !important;
  --el-table-header-bg-color: #f7f8fa;
  --el-table-border-color: #e5e6eb;
  box-shadow: none !important;
  border-radius: 0 !important;

  :deep(.el-table__header th) {
    background: #f7f8fa !important;
    font-weight: 600;
    font-size: 14px;
    border-radius: 0 !important;
    padding: 8px 0 !important;

    .cell {
      padding-left: 0px !important;
      padding-right: 0px !important;
    }
  }

  // 设置表格行高
  :deep(.el-table__body td) {
    border-radius: 0 !important;

    font-size: 14px;
    padding: 0 !important;
    // 列和单元格的边距
    .cell {
      padding: 0px 0px;
    }
  }

  // 去掉输入框边框
  :deep(.el-input__wrapper) {
    border-radius: 0 !important;
    box-shadow: none !important;
  }

  // 针对下拉选择框的所有相关元素去掉边框
  :deep(.el-select__wrapper) {
    border: none !important;
    box-shadow: none !important;
  }
}

.input-with-unit {
  position: relative;
}

:deep(.el-input__inner) {
  text-align: center;
}

.unit-text {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  color: #909399;
  font-size: 14px;
  pointer-events: none;
  z-index: 1;
}

.form-section {
  margin-bottom: 30px;
  padding: 20px;
  background: #fafbfc;
  border-radius: 8px;
  border: 1px solid #e5e6eb;

  .section-title {
    margin: 0 0 20px 0;
    font-size: 16px;
    font-weight: 600;
    color: #303133;
    padding-bottom: 10px;
    text-align: left;
    position: relative;
    display: inline-block;

    &::after {
      content: '';
      position: absolute;
      left: 0;
      bottom: 0;
      width: 100%;
      height: 2px;
      background: #409eff;
    }
  }

  &:last-child {
    margin-bottom: 0;
  }
}

.detection-results {
  margin: 20px 0;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e5e6eb;

  h3 {
    margin: 0 0 20px 0;
    font-size: 18px;
    font-weight: 600;
    color: #303133;
    text-align: left;
    padding-bottom: 10px;
    position: relative;
    display: inline-block;

    &::after {
      content: '';
      position: absolute;
      left: 0;
      bottom: 0;
      width: 100%;
      height: 2px;
      background: #67c23a;
    }
  }

  .result-summary {
    background: white;
    padding: 20px;
    border-radius: 6px;
    border: 1px solid #e5e6eb;
  }
}

.table-section {
  margin: 20px 0;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e5e6eb;

  .table-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
  }

  .table-title {
    margin: 0;
    font-size: 18px;
    font-weight: 600;
    color: #303133;
    text-align: left;
    padding-bottom: 10px;
    position: relative;
    display: inline-block;

    &::after {
      content: '';
      position: absolute;
      left: 0;
      bottom: 0;
      width: 100%;
      height: 2px;
      background: #409eff;
    }
  }

  .table-actions {
    display: flex;
    gap: 8px;
    margin-left: 20px;
  }
}

/* Vue3 + Element Plus 写法 */
:deep(.el-input__inner) {
  text-align: left !important;
}
</style>
